package com.lenovo.order_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.lenovo.order_service.api.req.*;
import com.lenovo.order_service.api.res.CreateOrderResVo;
import com.lenovo.order_service.api.res.FilterOrderResVo;
import com.lenovo.order_service.api.res.PageQueryOrderListResVo;
import com.lenovo.order_service.api.res.QueryOrderDetailResVo;
import com.lenovo.order_service.entity.Order;
import com.lenovo.order_service.enums.OrderStatus;
import com.lenovo.order_service.enums.ResultCode;
import com.lenovo.order_service.exception.BusinessException;
import com.lenovo.order_service.mapper.OrderMapper;
import com.lenovo.order_service.service.OrderService;
import com.lenovo.order_service.utils.PageBeanUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;


@Service
public class OrderServiceImpl implements OrderService {

    private final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrderMapper orderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CreateOrderResVo createOrder(CreateOrderReqVo condition) {
        CreateOrderResVo result = new CreateOrderResVo();
        // 1.解析header token
        if (condition.getCustomerId() == null) {
            Integer customerId = new Random().nextInt(10000);
            condition.setCustomerId(customerId.longValue());
            condition.setCustomerName("张" + customerId);
        }

        Order order = new Order();
        order.setOrderId(new Snowflake().nextId());
        order.setCustomerId(condition.getCustomerId());
        order.setCustomerName(condition.getCustomerName());
        order.setStatus(OrderStatus.PENDING.getStatus());

        // 2.计算价格
        order.setAmount(new BigDecimal(new Random().nextInt(1000)));

        // 3.落表
        // order.setCreatedAt(LocalDateTime.now());
        order.setCreatedAt(new Date());
        orderMapper.insert(order);

        result.setOrderId(order.getOrderId());
        return result;
    }

    @Override
    public QueryOrderDetailResVo queryOrderDetail(QueryOrderDetailReqVo condition) {
        /**
         * 伪代码
         * if (缓存命中) {
         *      return
         * } else {
         *      查询数据库,写入缓存
         *      return
         * }
         */
        Order order = orderMapper.selectByOrderId(condition.getOrderId());
        QueryOrderDetailResVo result = BeanUtil.copyProperties(order, QueryOrderDetailResVo.class);
        return result;
    }

    @Override
    public PageBeanUtil<PageQueryOrderListResVo> pageQueryOrderList(PageQueryOrderListReqVo condition) {
        PageBeanUtil<PageQueryOrderListResVo> result = new PageBeanUtil<>();

        Integer count = orderMapper.countQueryOrderList(condition);
        result.setPageSize(condition.getPageSize());
        result.setPageIndex(condition.getPageIndex());
        result.setPageCount(count);
        if (count > 0) {
            List<Order> orderList = orderMapper.pageQueryOrderList(condition);
            List<PageQueryOrderListResVo> list = BeanUtil.copyToList(orderList, PageQueryOrderListResVo.class);
            result.setData(list);
        }
        return result;
    }

    @Override
    public void updateOrderDetail(UpdateOrderDetailReqVo condition) {
        Order order = orderMapper.selectByOrderId(condition.getOrderId());
        if (order == null) {
            throw new BusinessException(ResultCode.INVALID_ORDER_ERROR.getCode(), ResultCode.INVALID_ORDER_ERROR.getName());
        }
        order.setStatus(condition.getStatus());
        orderMapper.updateByPrimaryKey(order);
    }

    @Override
    public void deleteOrderDetail(DeleteOrderDetailReqVo condition) {
        Order order = orderMapper.selectByOrderId(condition.getOrderId());
        if (order == null) {
            throw new BusinessException(ResultCode.INVALID_ORDER_ERROR.getCode(), ResultCode.INVALID_ORDER_ERROR.getName());
        }
        orderMapper.deleteByPrimaryKey(order.getId());
    }

    @Override
    public List<FilterOrderResVo> filterOrderDetail(FilterOrderReqVo condition) {
        List<FilterOrderResVo> result = new ArrayList<>();
        List<Order> orderList = orderMapper.filterOrderDetail(condition);
        if (CollectionUtils.isEmpty(orderList)) {
            return result;
        }
        result = BeanUtil.copyToList(orderList, FilterOrderResVo.class);
        return result;
    }

    @Override
    public void cleanPendingOrder() {
        orderMapper.cleanPendingOrder();
    }

    @Override
    public void countHourlyAmount() {
        Date nowDate = new Date();
        BigDecimal hourlyAmount = orderMapper.countHourlyAmount(nowDate);
        // 也可以记录到日志表中
        LOGGER.info("{} | 统计近一小时完成订单的总金额:{}", nowDate, hourlyAmount);
    }
}
